var qiniu = require('qiniu');
var express = require('express');
var config = require('./config.js');
var app = express();

app.configure(function () {
    app.use(express.static(__dirname + '/'));
});

var mac = new qiniu.auth.digest.Mac(config.ACCESS_KEY, config.SECRET_KEY);
var options = {
    scope: config.Bucket_Name,
    returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(fname)"}',
    forceSaveKey: true,
    saveKey: '${year}/${mon}/${day}/${etag}${ext}'
};
var putPolicy = new qiniu.rs.PutPolicy(options);

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);

app.use(express.urlencoded());


app.get('/uptoken', function (req, res, next) {
    var token = putPolicy.uploadToken(mac);
    res.header("Cache-Control", "max-age=0, private, must-revalidate");
    res.header("Pragma", "no-cache");
    res.header("Expires", 0);
    if (token) {
        res.json({
            uptoken: token
        });
    }
});

app.post('/downtoken', function (req, res) {

    var key = req.body.key,
        domain = req.body.domain;

    //trim 'http://'
    if (domain.indexOf('http://') != -1) {
        domain = domain.substr(7);
    }
    //trim 'https://'
    if (domain.indexOf('https://') != -1) {
        domain = domain.substr(8);
    }
    //trim '/' if the domain's last char is '/'
    if (domain.lastIndexOf('/') === domain.length - 1) {
        domain = domain.substr(0, domain.length - 1);
    }

    var config = new qiniu.conf.Config();
    var bucketManager = new qiniu.rs.BucketManager(mac, config);
    var privateBucketDomain = 'http://pvus064n8.bkt.clouddn.com/';
    var deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
    var privateDownloadUrl = bucketManager.privateDownloadUrl(privateBucketDomain, key, deadline);

    if (downloadToken) {
        res.json({
            downtoken: 'downloadToken',
            url: privateDownloadUrl
        })
    }
});

app.get('/', function (req, res) {
    res.render('index.html', {
        domain: config.Domain,
        uptoken_url: config.Uptoken_Url
    });
});

app.get('/wangEditor2', function (req, res) {
    res.render('wangEditor2.html', {
        domain: config.Domain,
        uptoken_url: config.Uptoken_Url
    });
});

app.get('/wangEditor3', function (req, res) {
    res.render('wangEditor3.html', {
        domain: config.Domain,
        uptoken_url: config.Uptoken_Url
    });
});

qiniu.conf.ACCESS_KEY = config.ACCESS_KEY;
qiniu.conf.SECRET_KEY = config.SECRET_KEY;

app.listen(config.Port, function () {
    console.log('Listening on port %d', config.Port);
});